package com.lotso.web.module.system.controller;

import com.google.common.collect.Lists;
import com.lotso.web.common.Result;
import com.lotso.web.module.base.AbstractController;
import com.lotso.web.module.system.entity.Menu;
import com.lotso.web.module.system.service.impl.MenuServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * ClassName: MenuController
 * Description: 菜单管理
 * Date: 2018/8/30 10:51 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Controller
@RequestMapping("/system/menu")
public class MenuController extends AbstractController {

    @Autowired
    private MenuServiceImpl menuService;

    /**
     * 进入菜单管理展示页面
     *
     * @return
     */
    @PreAuthorize("hasAuthority('menu:view')")
    @RequestMapping
    public String authorities() {
        return "module/system/menu";
    }

    /**
     * 查询菜单列表
     **/
    @PreAuthorize("hasAuthority('menu:view')")
    @ResponseBody
    @RequestMapping("/list")
    public Result<Menu> list() {
        List<Menu> menus = menuService.list();
        return new Result<>(menus);
    }


    /**
     * 进入添加|修改页面
     *
     * @param model
     * @return
     */
    @RequestMapping("editForm")
    public String editForm(Model model) {
        List<Menu> source = menuService.listMenu();
        List<Menu> menus = Lists.newArrayList();
        Menu.sortList(menus, source, Menu.ROOT_ID, true);
        model.addAttribute("menus", menus);
        return "module/system/menu_form";
    }

    /**
     * 添加菜单
     */
    @PreAuthorize("hasAuthority('menu:add')")
    @ResponseBody
    @RequestMapping("/add")
    public Result add(Menu menus) {
        if (menuService.add(menus)) {
            return Result.ok("添加成功");
        }
        return Result.error("添加失败");
    }

    /**
     * 修改菜单
     */
    @PreAuthorize("hasAuthority('menu:edit')")
    @ResponseBody
    @RequestMapping("/update")
    public Result update(Menu menus) {
        if (menuService.update(menus)) {
            return Result.ok("修改成功");
        }
        return Result.error("修改失败");
    }

    /**
     * 删除菜单
     */
    @PreAuthorize("hasAuthority('menu:delete')")
    @ResponseBody
    @RequestMapping("/delete")
    public Result delete(String meunId) {
        if (menuService.delete(meunId)) {
            return Result.ok("删除成功");
        }
        return Result.error("删除失败");
    }

}
